/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.UserProfile;

/**
 *
 * @author TranDangThuan
 */
public class AccountsController {
    public static boolean login(String user, String pass){
        Connection conn = DBUtility.openConnection();
        if (conn != null) {
            try {
                PreparedStatement ps = conn.prepareStatement("Select AccSerialNo from Accounts where AccSerialNo=? and AccPassword=?");
                ps.setString(1, user);
                ps.setString(2, pass);
                ResultSet rs = ps.executeQuery();
                boolean value = rs.next();
                DBUtility.closeConnection(conn);
                return value;
            } catch (Exception ex) {
                Logger.getLogger(AccountsController.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
            }
        }
        return false;
    }
    
    public static String getPermission(String user, String pass){
        Connection conn = DBUtility.openConnection();
        if (conn != null) {
            try {
                PreparedStatement ps = conn.prepareStatement("Select OfficerRole from Accounts where AccSerialNo=? and AccPassword=?");
                ps.setString(1, user);
                ps.setString(2, pass);
                ResultSet rs = ps.executeQuery();
                rs.next();
                String role = rs.getString(1);
                DBUtility.closeConnection(conn);
                return role;
            } catch (SQLException ex) {
                Logger.getLogger(AccountsController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }
    
    public static UserProfile getUserProfile(String serial) {
        Connection conn = DBUtility.openConnection();
        UserProfile profile = new UserProfile();
        if (conn != null) {
            try {
                CallableStatement cs = conn.prepareCall("{call sp_GetCurrentUserBySerial(?)}");
                cs.setString(1, serial);
                ResultSet rs = cs.executeQuery();
                if (rs.next()) {
                    profile.setPassword(rs.getString("AccPassword"));
                    profile.setPicture(rs.getString("AccPicture"));
                    profile.setAddress(rs.getString("OfficerAddress"));
                    profile.setPhone(rs.getString("OfficerPhone"));
                }
                DBUtility.closeConnection(conn);
            } catch (SQLException ex) {
                Logger.getLogger(AccountsController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return profile;
    }
}
